<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">


      <el-form-item label="订单号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable>
          <el-option
              v-for="dict in ordertype"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-input
            v-model="queryParams.supplierId"
            placeholder="请输入供应商"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单金额" prop="payableAmount">
        <el-input
            v-model="queryParams.payableAmount"
            placeholder="请输入订单金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="receiptOrderStatus">
        <el-input
            v-model="queryParams.receiptOrderStatus"
            placeholder="请输入订单状态"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['order:saleorder:add']"
        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['order:saleorder:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['order:saleorder:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['order:saleorder:export']"
        >导出
        </el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="saleorderList" @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="${comment}" align="center" prop="id" />-->
      <el-table-column label="订单号" align="center" prop="orderNo" :show-overflow-tooltip="true">
        <template #default="scope">

          <span style="color: #1c84c6" @click="itemMenu(scope.row.id)">{{ scope.row.orderNo }}</span>

        </template>

      </el-table-column>

      <el-table-column label="订单类型" align="center" prop="orderType">
        <template #default="scope">
          <dict-tag :options="ordertype" :value="scope.row.orderType"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="供应商" align="center" prop="supplierId" />-->
      <el-table-column label="供应商编号" align="center" prop="supplierNo"/>
      <el-table-column label="供应商名称" align="center" prop="supplierName"/>
      <el-table-column label="订单金额" align="center" prop="payableAmount"/>

      <el-table-column label="订单状态" align="center" prop="receiptOrderStatus">
        <template #default="scope">
          <dict-tag :options="orderstatus" :value="scope.row.receiptOrderStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建人" align="center" prop="createName"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateName"/>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['order:saleorder:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['order:saleorder:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" v-model="open" width="1300px" append-to-body>
      <el-form ref="saleorderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" style="width: 400px" placeholder="请输入订单号"/>
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="form.orderType" style="width: 400px" placeholder="请选择订单类型">
            <el-option
                v-for="dict in ordertype"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <el-select
              v-model="supplierId"
              filterable
              placeholder="请输入供应商"
              style="width: 240px"
              @click="select()"
          >
            <el-option
                v-for="item in supplierArr"
                :key="item.id"
                :label="item.supplierName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="客户" prop="customerId">
          <el-select
              v-model="customerId"
              filterable
              placeholder="请输入客户"
              style="width: 240px"
              @click="select()"
          >
            <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单金额" prop="payableAmount">
          <el-input v-model="form.payableAmount" style="width: 400px" placeholder="请输入订单金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" style="width: 400px" placeholder="请输入备注"/>
        </el-form-item>
        <el-divider content-position="center">采购订单详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddWmssaleorderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteWmssaleorderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="checkedWmssaleorderDetail" :row-class-name="rowWmssaleorderDetailIndex"
                  @selection-change="handleWmssaleorderDetailSelectionChange" ref="wmssaleorderDetail">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料编号" prop="id" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.itemNo" placeholder="请选择物料"/>
            </template>

          </el-table-column>
          <el-table-column label="物料名称" prop="itemName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.itemName"/>
            </template>

          </el-table-column>

          <el-table-column label="计划数量" prop="planNum" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.planNum" placeholder="请输入计划数量"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"/>
            </template>
          </el-table-column>

          <el-table-column label="所属库位" prop="areaId" width="150">
            <template #default="scope">
              <el-select
                  v-model="areaId"
                  filterable
                  placeholder="请输入库位"
                  style="width: 240px"
                  @click="selectArea()"
              >
                <el-option
                    v-for="item in areaList"
                    :key="item.id"
                    :label="item.areaName"
                    :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--物料弹窗-->

    <el-dialog v-model="dialogVisible" title="物料管理" width="1100" draggable>

      <el-table v-loading="loading1" :data="itemList" @selection-change="handleSelectionChange1">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="编号" align="center" prop="id"/>
        <el-table-column label="货号" align="center" prop="itemNo"/>
        <el-table-column label="名称" align="center" prop="itemName"/>
        <el-table-column label="规格" align="center" prop="specification"/>
        <el-table-column label="分类" align="center" prop="itemType"/>
        <el-table-column label="单位" align="center" prop="unit"/>
        <el-table-column label="单价" align="center" prop="unitPrice"/>
        <el-table-column label="所属货架" align="center" prop="rackId"/>
        <el-table-column label="库区编号" align="center" prop="areaId"/>
        <el-table-column label="所属仓库" align="center" prop="warehouseId"/>
        <el-table-column label="安全库存" align="center" prop="quantity"/>
        <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期" align="center" prop="expiryDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次" align="center" prop="batch"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="total1>0"
          :total="total1"
          v-model:page="queryParams1.pageNum"
          v-model:limit="queryParams1.pageSize"
          @pagination="getItemList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="itemSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!--子表弹窗-->
    <el-drawer
        v-model="itemMenutable"
        direction="btt"
        size="50%">
      <el-table :data="saleorderDetail">

        <el-table-column type="index" label="行号" width="150"/>
        <el-table-column prop="itemNo" label="物料编号" width="150"/>
        <el-table-column property="itemName" label="物料名称" width="200"/>
        <el-table-column property="planNum" label="计划数量"/>
        <el-table-column property="realNum" label="已处理数量"/>
        <el-table-column property="specification" label="规格"/>
        <el-table-column property="unit" label="单位"/>
      </el-table>

    </el-drawer>

  </div>
</template>

<script setup name="Saleorder">
import {listItem, getItem, delItem, addItem, updateItem} from "@/api/system/item";
import {
  listSaleorder,
  getsaleorder,
  delsaleorder,
  addsaleorder,
  updatesaleorder,
  isObjectInArray
} from "@/api/order/saleorder";
import {listSupplier} from "@/api/system/supplier";
import {listArea} from "../../../api/system/area";
import {ElMessage, ElMessageBox, ElDrawer} from "element-plus";
import {reactive, ref} from 'vue'
import {listCustomer, listCustomerAll} from "../../../api/system/customer";


const dialogVisible = ref(false)
const dialogOverflowVisible = ref(false)
const {proxy} = getCurrentInstance();
const {ordertype, orderstatus} = proxy.useDict('ordertype', 'orderstatus');
const saleorderList = ref([]);
const wmssaleorderDetailList = ref([]);

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedWmssaleorderDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

//物料弹窗
const itemList = ref([]);
const loading1 = ref(true);
const total1 = ref(0);
const supplierId = ref();
const customerId = ref();
//库位id
const areaId = ref();
//子表抽屉是否显示
const itemMenutable = ref(false);
//子表订单列表
const saleorderDetail = ref([]);

//存放新增修改弹框订单详情信息被选中的数据
const  checkedWmssaleorderDelectDetail = ref([]);
//供应商列表
const supplierArr = ref([]);
//存储库位列表
const areaList = ref([]);
function select() {
  listSupplier().then(response => {
    supplierArr.value = response.rows;


  })

}
//客户列表
const customerList = ref([]);
function getCustomerList() {
  loading.value = true;
  listCustomer(queryParams.value).then(response => {
    customerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });

}

//获取库位列表
function selectArea() {
  listArea().then(response => {
    areaList.value = response.rows;
  })

}


const data1 = reactive({
  form1: {},
  // queryParams1物料弹窗分页参数
  queryParams1: {
    pageNum: 1,
    pageSize: 10,
    itemNo: null,
    itemName: null,
    itemType: null,
    rackId: null,
    areaId: null,
    warehouseId: null,
    createTime: null,
  }, rules1: {}
});
const {queryParams1, form1, rules1} = toRefs(data1);

/** 查询物料列表 */
function getItemList() {
  loading1.value = true;
  listItem(queryParams1.value).then(response => {
    itemList.value = response.rows;
    total1.value = response.total;
    loading1.value = false;
    console.log("物料：" + itemList.value[0].itemNo)
  });
}

//存储物料弹窗被选中的数据
const ids1 = ref([]);
//物料弹窗选中状态变量
const single1 = ref(true);
const multiple1 = ref(true);

// 多选框选中数据物料弹窗
function handleSelectionChange1(selection) {
  ids1.value = selection.map(item => {
    let re = {};
    re.itemId = item.id;
    re.itemName = item.itemName;
    re.itemNo = item.itemNo;
    return re;
  });
  single1.value = selection.length != 1;
  multiple1.value = !selection.length;
}

//物料弹窗确认按钮
const itemSubmit = () => {

  for (let item of ids1.value) {
    //判断物料是否已存在
    if (isObjectInArray(checkedWmssaleorderDetail.value, item, 'itemId')) {
      ElMessage.error("该物料已存在")
    } else {//不存在，则追加物料到checkedWmssaleorderDetail中并关闭物料弹框
      checkedWmssaleorderDetail.value.push(item);
      dialogVisible.value = false;
      single1.value = false;
      multiple1.value = false;
    }
  }

}

//采购订单列表
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: "createTime",
    isAsc: "desc",
    id: null,
    orderNo: null,
    orderType: null,
    supplierId: null,
    payableAmount: null,
    receiptOrderStatus: null,
  },
  rules: {
    // delFlag: [
    //   { required: true, message: "删除标识不能为空", trigger: "blur" }
    // ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询采购订单列表 */
function getList() {
  loading1.value = true;
  listSaleorder(queryParams.value).then(response => {
    saleorderList.value = response.rows;
    console.log("采购订单列表" + saleorderList.value[0].supplierId)
    total.value = response.total;
    loading.value = false;
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();

}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    orderType: null,
    supplierId: null,
    supplierNo: null,
    supplierName: null,
    payableAmount: null,
    receiptOrderStatus: null,
    remark: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    warehouseId: null
  };
  wmssaleorderDetailList.value = [];
  proxy.resetForm("saleorderRef");
  ids1.value = [];
  supplierId.value = '';
  checkedWmssaleorderDetail.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  getCustomerList();
  open.value = true;
  title.value = "添加采购订单";

  listSupplier.then(response => {
    supplierArr.value = response.rows;
  })
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  queryParams.value.id = _id;
  console.log("di--:" + _id);
  getsaleorder(_id).then(response => {
    checkedWmssaleorderDetail.value = response.data;
    open.value = true;
    title.value = "修改采购订单";
  });
  listSaleorder(queryParams.value).then(response => {
    form.value.supplierName = response.rows[0].supplierName;
    form.value.supplierid = response.rows[0].supplierid;
    form.value.id = response.rows[0].id;
    form.value.orderNo = response.rows[0].orderNo;
    form.value.orderType = response.rows[0].orderType;
    form.value.orderType = response.rows[0].receiptOrderStatus;
    form.value.remark = response.rows[0].remark;
    supplierId.value = response.rows[0].supplierId;
  });

}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["saleorderRef"].validate(valid => {
    form.value.supplierId = supplierId.value;
    form.value.areaId = areaId.value;
    if (valid) {
      form.value.wmssaleorderDetailList = checkedWmssaleorderDetail.value;

      if (form.value.id != null) {
        updatesaleorder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addsaleorder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          checkedWmssaleorderDetail.value = [];
          ids1.value = [];
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除采购订单编号为"' + _ids + '"的数据项？').then(function () {
    return delsaleorder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}


//获取子表列表
function itemMenu(id) {
  getsaleorder(id).then(response => {
    saleorderDetail.value = response.data;
    console.log("子表数据" + saleorderDetail.value);


  })

  itemMenutable.value = true


}

/** 采购订单详情序号 */
function rowWmssaleorderDetailIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 采购订单详情添加按钮操作 */
function handleAddWmssaleorderDetail() {
  let obj = {};
  obj.itemId = "";
  obj.planNum = "";
  obj.realNum = "";
  obj.remark = "";
  obj.createBy = "";
  obj.createTime = "";
  obj.updateBy = "";
  obj.updateTime = "";
  obj.warehouseId = "";
  obj.areaId = "";
  wmssaleorderDetailList.value.push(obj);
  getItemList();
  dialogVisible.value = true;
}

/** 采购订单详情删除按钮操作 */
function handleDeleteWmssaleorderDetail() {
  if (checkedWmssaleorderDetail1.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的采购订单详情数据");
  } else {
    const wmssaleorderDetails = checkedWmssaleorderDetail.value;
    const checkedWmssaleorderDetails = checkedWmssaleorderDetail1.value;
    checkedWmssaleorderDetail.value = wmssaleorderDetails.filter(function (item) {
      return checkedWmssaleorderDetails.indexOf(item.index) == -1
    });
  }
}





/** 复选框选中数据 */
function handleWmssaleorderDetailSelectionChange(selection) {
  checkedWmssaleorderDelectDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/saleorder/export', {
    ...queryParams.value
  }, `saleorder_${new Date().getTime()}.xlsx`)
}


</script>

<style>

.el-pagination {
  margin-right: 30px;
}

/*.el-table_1_column_2 { display:inline-block;width: 80px;}*/
/*.cell{width: 80px;}*/
.el-drawer__header {
  margin: 0
}
</style>
